<template>
  <div id="app" class="maintenance">
    <!-- 头部导航 -->
    <van-nav-bar left-text="返回" left-arrow @click-left="onClickBack">
      <template slot="title"> <span>报工详情</span> </template>
      <template slot="right">
        <van-button class="van-button-nav" plain type="primary" @click="showMachineSelectPop = true">上报</van-button>
        <call-worker v-if="showCallWorker" style="margin-left: 1vw;height: 6.5vh;" :dep-id="depId"></call-worker>
      </template>
    </van-nav-bar>

    <van-row type="flex" align="center">
      <van-col>
        <van-field size="large" v-model="queryParams.beginAt" label="开始时间:" label-align="right" readonly placeholder="点击选择时间" @click="showDatePicker = true"/>
      </van-col>
      <van-col>
        <van-field size="large" v-model="queryParams.endAt" label="结束时间:" label-align="right" readonly placeholder="点击选择时间" @click="showDatePicker = true"/>
      </van-col>
      <van-col span="4">
        <van-popover v-model:show="showMachineQueryPop" :actions="machineData" @select="selectMachineParamFn">
          <template #reference>
<!--            <van-button style="font-size: 18px; height: 35px; width: 15vw;" @click="showMachineQueryPop = true">{{queryParams.machineType}}</van-button>-->
            <van-field clearable clear-trigger="always" style="font-size: 18px; height: 35px; width: 15vw;" v-model="queryParams.machineType" placeholder="请选择机台类型" @focus="showMachineQueryPop = true"></van-field>
          </template>
        </van-popover>
      </van-col>
      <van-col span="4">
        <van-popover v-model:show="showStatusQueryPop" :actions="statusEnum" @select="selectStatusParamFn">
          <template #reference>
            <van-button style="font-size: 18px; height: 35px; width: 15vw;" @click="showStatusQueryPop = true">{{getEnumLabel(statusEnum, queryParams.status)}}</van-button>
          </template>
        </van-popover>
      </van-col>
      <van-col>
        <van-button plain style="font-size: 18px; height: 35px; width: 6vw;" type="info" @click="() => loadMaintenanceRecordFn()">查询</van-button>
      </van-col>
    </van-row>
    <van-calendar :min-date="minDate" :max-date="maxDate" v-model="showDatePicker" type="range" @confirm="confirmDateFilterFn"></van-calendar>

    <!-- 维保记录表格 -->
    <div style="padding: 15px; height:78%;">
      <div>
        <van-row class="craft-row first" type="flex" justify="space-between" align="center">
          <van-col class="craft-row-col title"><span>原因</span></van-col>
          <van-col class="craft-row-col title main"><span>机台类型</span></van-col>
          <van-col class="craft-row-col title"><span>机台号</span></van-col>
          <van-col class="craft-row-col title"><span>上报人</span></van-col>
          <van-col class="craft-row-col title dateTime"><span>上报时间</span></van-col>
          <van-col class="craft-row-col title"><span>处理人</span></van-col>
<!--          <van-col class="craft-row-col title dateTime"><span>开始时间</span></van-col>-->
          <van-col class="craft-row-col title dateTime"><span>完成时间</span></van-col>
          <van-col class="craft-row-col title"><span>状态</span></van-col>
          <van-col class="craft-row-col title opt"><span>操作</span></van-col>
        </van-row>
      </div>
      <div style="max-height: 94%; overflow: auto">
        <van-row class="craft-row" :class="{ selected: curRowIndex === index }" type="flex" justify="space-between" align="center" v-for="(row, index) in maintenanceData" :key="row.id" @click="selectMachineRowFn(row, index)">
          <van-col class="craft-row-col">
            <span> {{ row.optType ? row.optType : "&nbsp;" }}</span>
          </van-col>
          <van-col class="craft-row-col main">
            <span> {{ row.machineType ? row.machineType : "&nbsp;"  }}</span>
          </van-col>
          <van-col class="craft-row-col">
            <span> {{ row.no ? row.no : "&nbsp;" }}</span>
          </van-col>
          <van-col class="craft-row-col">
            <span> {{ row.reporterName ? row.reporterName : "&nbsp;" }}</span>
          </van-col>
          <van-col class="craft-row-col dateTime">
            <span> {{ row.createAt ? row.createAt : "&nbsp;" }}</span>
          </van-col>
          <van-col class="craft-row-col">
            <span> {{ row.operatorName ? row.operatorName : "&nbsp;" }}</span>
          </van-col>
<!--          <van-col class="craft-row-col dateTime">-->
<!--            <span> {{ row.acceptAt ? row.acceptAt : "&nbsp;" }}</span>-->
<!--          </van-col>-->
          <van-col class="craft-row-col dateTime">
            <span> {{ row.finishedAt ? row.finishedAt : "&nbsp;" }}</span>
          </van-col>
          <van-col class="craft-row-col">
            <span> {{ row.status ? getEnumLabel(statusEnum, row.status) : "&nbsp;" }}</span>
          </van-col>
          <van-col class="craft-row-col opt">
<!--            <van-button v-if="row.status == 1" type="info" @click="maintenanceAcceptFn(row.id)">接单</van-button>-->
            <van-button v-if="getInfo().userId == row.reporterId" type="danger"  @click.stop="cancelRecordFn(row.id)">取消</van-button>
            <van-button v-if="row.status == 1 || row.status == 2 || row.status == 99" type="primary" style="margin-left: 1vw;" @click.stop="showFinishOptPopupFn(row, index)">处理</van-button>
          </van-col>
        </van-row>
      </div>
    </div>
    <van-pagination v-model="queryParams.pageNumber" :total-items="queryParams.totalNum" :items-per-page="queryParams.pageSize" :show-page-size="10" force-ellipses @change="loadMaintenanceRecordFn" />

    <!-- 选择 -->
    <van-popup style="width:40vw;" v-model="showMachineSelectPop" round position="left">
      <van-picker ref="jobDataPickerRef" :visible-item-count="18" :loading="loading" show-toolbar :columns="machineData" @cancel="showMachineSelectPop = false" @confirm="machineSelectConfirmFn"/>
    </van-popup>

    <!-- 操作确认框 -->
    <van-popup v-model="showFinishOptPopup" :closeable="true" :close-on-click-overlay="false">
      <div class="finish-popup-body">
        <van-field v-model="changeParams.optRemark" :readonly="!showFinishOptBtn" rows="7" placeholder="请输入处理留言" type="textarea" maxlength="500" show-word-limit autosize></van-field>
        <div v-if="showFinishOptBtn" style="width: 100%; display: flex; justify-content: center; align-items: center; margin-top:1vh;padding:1vh 1vw;">
          <van-button style="width: 10vw" type="warn" @click="maintenanceFinishFn(5)">有问题</van-button>
          <van-button style="width: 10vw;margin-left: 2vw;" type="info" @click="maintenanceFinishFn(3)">确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {deepCopy, openWin} from "@/utils";
import {statusEnum, getEnumLabel} from "@/utils/common";
import dayjs from "dayjs";
import {
  cancelRecord,
  loadMachineType,
  loadMaintenanceRecordFn,
  maintenanceAccept, maintenanceFinish,
  maintenanceReport
} from "@/views/maintenance/maintenance";
import {getRefreshToken} from "@/api/login";
import {getInfo, setInfo} from "@/utils/auth";
import CallWorker from "@/views/call-worker/App";

export default {
  name: "maintenance",
  components: {CallWorker},
  props: {
    depId: {
      type: String,
      default: "45",    //后端配置车间ID
    }
  },
  data() {
    return {
      statusEnum: deepCopy(statusEnum),

      /* 查询条件 */
      showMachineQueryPop: false,
      showStatusQueryPop: false,
      queryParams: {
        depId: this.depId,
        machineType: "请选择机台类型",
        beginAt: dayjs().subtract(3, "day").format("YYYY-MM-DD"),
        endAt: dayjs().add(1, "day").format("YYYY-MM-DD"),
        status: 1,
        pageNumber: 1,
        pageSize: 18,
        totalNum: 0
      },

      //日期参数
      minDate: new Date(2021, 0, 1),
      maxDate: new Date(2025, 10, 1),
      showDatePicker: false,

      /* 增改 */
      changeParams: {
        id: "",
        optType: "维修",
        depId: this.depId,
        machineType: "",
        no: "",
        optRemark: "",
        status: 1,
      },
      //筛选机台
      showMachineSelectPop: false,
      loading: false,
      machineData: [],

      /* 分页表格 */
      curRowIndex: -1,
      maintenanceData: [],

      /* 完成对话框 */
      showFinishOptPopup: false,
      showFinishOptBtn: false,

      /* 启用呼叫 api ready后加载 */
      showCallWorker: false,

    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    getInfo,
    getEnumLabel,
    initFn(that) {
      let sessionTimer = setInterval(() => {
        getRefreshToken({
          secret: getInfo().secret,
        }, (res) => {
          setInfo(res);
        });
      }, 600000);
      // 监听页面消失的时候，关掉页面就可以了
      window.api.addEventListener({
        name: "viewdisappear",
      }, function () {
        clearInterval(sessionTimer);
        window.api.closeWin();
      });

      //设置未完成选项
      that.statusEnum.splice(0, 0, {
        label: "未完成",
        text: "未完成",
        value: 99,
      });
      that.statusEnum.splice(that.statusEnum.findIndex(item => item.value == 1), 1);
      that.statusEnum.splice(that.statusEnum.findIndex(item => item.value == 2), 1);
      that.statusEnum.splice(that.statusEnum.findIndex(item => item.value == 4), 1);
      let errFinishStatus = that.statusEnum.find(item => item.value == 5);
      errFinishStatus.label = "有问题"
      errFinishStatus.text = errFinishStatus.label;
      that.queryParams.status = 99;

      //加载机台数据
      that.machineFilterFn("织造-");

      //加载维保记录
      that.loadMaintenanceRecordFn(1);

      that.showCallWorker = true;
    },
    // 返回
    onClickBack() {
      openWin("index");
    },
    //确认选中日历区间
    confirmDateFilterFn(date) {
      const that = this;
      that.showDatePicker = false;
      let [start, end] = date;
      that.queryParams.beginAt = dayjs(start).format("YYYY-MM-DD");
      that.queryParams.endAt = dayjs(end).format("YYYY-MM-DD");
    },

    //选择机台参数
    selectMachineParamFn(item) {
      const that = this;
      that.queryParams.machineType = item.text;
    },
    //选择状态
    selectStatusParamFn(item) {
      const that = this;
      that.queryParams.status = item.value
    },

    //筛选机台
    machineFilterFn(value) {
      const that = this;
      that.loading = true;
      loadMachineType({
        type: value
      }, res => {
        that.loading = false;
        that.machineData.splice(0, that.machineData.length);
        res.forEach(machine => {
          machine.text = machine.propertyName;
          machine.value = machine.propertyName;
          machine.children = [];
          machine.propertyValue.split(",").forEach(no => {
            machine.children.push({
              text: no,
              value: no
            });
          });
          that.machineData.push(machine);
        });
      });
    },

    //选中机台 上报
    machineSelectConfirmFn(items) {
      const that = this;
      that.changeParams.machineType = items[0];
      that.changeParams.no = items[1];
      maintenanceReport(that.changeParams, () => {
        that.$toast.success("操作成功");
        that.queryParams.status = 1;  //恢复查询
        that.queryParams.machineType = that.changeParams.machineType;
        that.queryParams.beginAt = dayjs().subtract(3, "day").format("YYYY-MM-DD");
        that.queryParams.endAt = dayjs().add(1, "day").format("YYYY-MM-DD");
        that.loadMaintenanceRecordFn(1);
        that.showMachineSelectPop = false;
      });
    },

    //加载报工列表
    loadMaintenanceRecordFn(pageNum) {
      const that = this;
      that.loading = true;
      if(pageNum) {
        that.queryParams.pageNumber = pageNum;
      }
      if("请选择机台类型" == that.queryParams.machineType) {
        that.queryParams.machineType = "";
      }
      loadMaintenanceRecordFn(that.queryParams, res => {
        that.loading = false;
        that.maintenanceData.splice(0, that.maintenanceData.length);
        that.queryParams.totalNum = res.totalRow;
        res.list.forEach(row => {
          if(row.status == 1 || row.status == 2) {
            row.status = 99;
          }
          that.maintenanceData.push(row);
        });
      });
    },

    //选中记录行
    selectMachineRowFn(row, index) {
      const that = this;
      that.curRowIndex = index;
      that.showFinishOptPopup = true;
      if(row.status == 1 || row.status == 2 || row.status == 99) {
        that.showFinishOptBtn = true;
      } else {
        that.showFinishOptBtn = false;
      }
      that.changeParams.optRemark = row.optRemark;
    },

    //维保接任务
    // maintenanceAcceptFn(recordId) {
    //   const that = this;
    //   maintenanceAccept({
    //     recordId: recordId
    //   }, () => {
    //     that.$toast.success("操作成功");
    //     that.loadMaintenanceRecordFn();
    //   });
    // },

    //处理弹窗
    showFinishOptPopupFn(row, index) {
      const that = this;
      that.changeParams.id = row.id;
      that.selectMachineRowFn(row, index);
    },
    //维保处理任务
    maintenanceFinishFn(optFlag) {
      const that = this;
      that.changeParams.status = optFlag;
      maintenanceFinish(that.changeParams, () => {
        that.$toast.success("操作成功");
        that.showFinishOptPopup = false;
        that.loadMaintenanceRecordFn();
      });
    },

    //撤销记录
    cancelRecordFn(recordId) {
      const that = this;
      cancelRecord({recordId: recordId}, () => {
        that.$toast.success("撤销成功");
        that.loadMaintenanceRecordFn();
      })
    }
  }
}
</script>

<style lang="scss">
.maintenance {
  margin-top: 5px;
  //导航栏样式
  .van-nav-bar {
    height: 60px;
    .van-icon {
      width: 50px;
      height: 50px;
    }
    .van-nav-bar__right {
      margin-top: 5px;
    }
    .van-button-nav {
      font-size: 28px;
      width: 150px;
    }
  }

  .van-field__label {
    font-size: 22px;
  }
  .van-field__body input {
    font-size: 22px;
    width: 150px;
  }

  .van-form {
    .van-search__label {
      font-size: 22px;
    }
    .van-field__body input {
      font-size: 22px;
      width: 300px;
    }
    .van-icon-search {
      font-size: 22px;
    }
  }

  //表格样式
  .craft-row {
    border-left: #323233 1px solid;
    line-height: 38px;
    height: 38px;
    &.selected {
      background-color: #e6a23c;
    }
    &.first {
      border-top: #323233 1px solid;
    }
  }
  .craft-row-col {
    text-align: center;
    font-size: large;
    height: 38px;
    overflow: hidden;
    flex: 1;
    border-right: #323233 1px solid;
    border-bottom: #323233 1px solid;
    .van-button {
      height: 38px;
    }
    &.title {
      font-weight: bolder;
    }
    &.dateTime {
      flex: 0 0 200px;
    }
    &.main {
      flex: 0 0 180px;
    }
    &.opt {
      flex: 0 0 180px;
      display: flex;
      justify-content: center;
      align-items: center;
      button {
        height: 30px;
      }
    }
  }

  //picker选中
  .van-picker-column__item--selected {
    font-size: 32px;
    color: #08936c;
    font-weight: bold;
  }
  //picker取消
  .van-picker__cancel {
    font-size: 32px;
    font-weight: bold;
    color: red;
  }
  //picker确认
  .van-picker__confirm {
    font-size: 32px;
    font-weight: bold;
    color: #001e80;
  }
  //完成弹窗
  .finish-popup-body {
    padding: 1vh 2vw;
    min-width: 40vw;
    min-height: 40vh;
    .van-field__label {
      font-size: 1.5rem;
    }
    .van-field__body {
      .van-field__control {
        text-align: start;
        font-size: 1.5rem;
      }
    }
  }
}
</style>